<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="解析组名称" prop="analysisGroupName">
        <el-input
          v-model="queryParams.analysisGroupName"
          placeholder="请输入解析组名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="false"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="page" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="解析组编码" prop="id" :show-overflow-tooltip="true" width="400"/>
      <el-table-column label="解析组名称" prop="analysisGroupName" :show-overflow-tooltip="true" width="500"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getPage"
    />

    <!-- 添加或修改解析组元素顺序对话框 -->
    <el-dialog :visible.sync="open" :title="title" width="1000px" append-to-body>
      <div class="left-board">
        <el-scrollbar class="left-scrollbar">
          <div class="components-list">
            <div class="components-title">
              <svg-icon icon-class="component"/>
              元素列表
            </div>
            <draggable
              class="components-draggable" :list="elementList"
              :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
              draggable=".components-item" :sort="false">
              <div v-for="(element, index) in elementList" :key="index" class="components-item"
                   @click="addComponent(element)">
                <div class="components-body">
                  {{ element.identifierMsg }}
                </div>

              </div>
            </draggable>
          </div>
        </el-scrollbar>
      </div>
      <div class="center-board">

        <el-scrollbar class="center-scrollbar">

          <el-form size="medium" ref="form" :model="form" :rules="rules">
            <el-tag type="danger" class="tag-class">解析组元素顺序必须与报文数据顺序一致，否则可能会导致解析失败。</el-tag>
            <el-form-item label="解析组编码" prop="id" v-show="false">
              <el-input v-model="form.id" placeholder="请输入解析组"></el-input>
            </el-form-item>
            <el-form-item label="解析组名称" prop="analysisGroupName">
              <el-input v-model="form.analysisGroupName" placeholder="请输入解析组名称"></el-input>
            </el-form-item>
            <draggable class="components-draggable" :list="drawingList" :animation="340" group="componentsGroup">
              <div v-for="(element, index) in drawingList" :key="index" class="components-item drawing-item">
                <div class="components-body ">
                  <span v-text="element.identifierMsg"></span>
                </div>
                <el-button type="primary" class="btn-class" icon="el-icon-copy-document" circle
                           @click="copyComponent(element, index)"></el-button>
                <el-button type="danger" class="btn-class" icon="el-icon-delete" circle
                           @click="deleteComponent(index)"></el-button>
              </div>
            </draggable>
            <div v-show="!drawingList.length" class="empty-info">
              从左侧拖入或点选元素组件进行解析组设计
            </div>
          </el-form>
        </el-scrollbar>
      </div>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import draggable from 'vuedraggable';
  import {inputComponents, selectComponents, layoutComponents, formConf} from '@/utils/generator/config'
  import {
    getAllElementList
  } from "@/api/analysisconfigure/element";
  import {
    page,
    getElement,
    getElementGroupList,
    insertElementGroup,
    updateElementGroup,
    delElementGroup,
  } from "@/api/analysisconfigure/elementgroup";

  export default {
    components: {
      draggable,
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        page: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          identifierMsg: undefined,
          identifierValue: undefined,
          codingFormat: '',
          integerBit: undefined,
          radixPointBit: undefined,
          tableName: undefined,
          fieldName: undefined,
          fieldUnit: undefined,
        },
        dialogType: '',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          analysisGroupId: undefined,
          analysisGroupName: undefined,
        },
        // 表单校验
        rules: {
          analysisGroupName: [{
            required: true,
            message: '请输入解析组名称',
            trigger: 'blur'
          }],
        },
        elementList: [],
        drawingList: []
      };
    },
    created() {
      this.getPage();
    },
    methods: {
      /** 查询分页列表 */
      getPage() {
        this.loading = true;
        page(this.queryParams).then(response => {
            this.page = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      getAllElementList() {
        getAllElementList(this.queryParams).then(response => {
          this.elementList = response.data;
        });
      },
      addComponent(item) {
        let length = this.drawingList.length;
        this.drawingList.splice(length, 0, item);
      },
      copyComponent(element, index) {
        this.drawingList.splice(index, 0, element);
      },
      deleteComponent(index) {
        this.drawingList.splice(index, 1);
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          ids: undefined,
          analysisGroupName: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getPage();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.getAllElementList();
        this.reset();
        this.title = "新增元素解析组中各个元素的顺序";
        this.drawingList = []
        this.open = true;
        this.dialogType = "add";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        this.getAllElementList();
        getElementGroupList(id).then(response => {
          const drawingList = response.data;
          if(drawingList == null || drawingList === "") {
            this.drawingList = [];
          } else {
            this.drawingList = drawingList;
          }
          this.form.id = row.id;
          this.form.analysisGroupName = row.analysisGroupName;
          this.open = true;
          this.title = "修改元素解析组中各个元素的顺序";
          this.dialogType = "update";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        let that = this;
        let drawingList = that.drawingList;
        let analysisIds = [];

        drawingList.forEach(item => {
          analysisIds.push(item.id);
        });
        that.$refs["form"].validate(valid => {
          if (valid) {
            const analysisGroupName = that.form.analysisGroupName;
            const id = that.form.id;
            if ('update' === that.dialogType) {
              updateElementGroup(analysisIds, id, analysisGroupName).then(response => {
                that.$modal.msgSuccess("修改成功");
                that.open = false;
                that.getPage();
              });
            } else {
              insertElementGroup(analysisIds, analysisGroupName).then(response => {
                that.$modal.msgSuccess("新增成功");
                that.open = false;
                that.getPage();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function () {
          return delElementGroup(id);
        }).then(() => {
          this.getPage();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },
    }
  };
</script>
<style lang='scss' scoped="scoped">
  body, html {
    margin: 0;
    padding: 0;
    background: #fff;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
  }

  input, textarea {
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
  }

  .tag-class{
    font-size: 16px;
    margin: 3px 0 10px 3%;
  }
  // home

  .left-scrollbar .el-scrollbar__wrap {
    box-sizing: border-box;
    overflow-x: hidden !important;
    margin-bottom: 0 !important;
  }

  .center-tabs {
    .el-tabs__header {
      margin-bottom: 0 !important;
    }
    .el-tabs__item {
      width: 50%;
      text-align: center;
    }
    .el-tabs__nav {
      width: 100%;
    }
  }

  .custom-tree-node {
    width: 100%;
    font-size: 14px;
    .node-operation {
      float: right;
    }
    i[class*="el-icon"] + i[class*="el-icon"] {
      margin-left: 6px;
    }
    .el-icon-plus {
      color: #409EFF;
    }
    .el-icon-delete {
      color: #157a0c;
    }
  }

  .left-scrollbar .el-scrollbar__view {
    overflow-x: hidden;
  }

  $selectedColor: #f6f7ff;
  $lighterBlue: #409EFF;

  .container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .components-list {
    padding: 8px;
    box-sizing: border-box;
    height: 100%;
    .components-item {
      display: inline-block;
      width: 48%;
      margin: 1%;
      transition: transform 0ms !important;
    }
  }

  .drawing-item {
    margin: 5px 0;
    display: flex;

  }

  .components-draggable {
    padding-bottom: 20px;
  }

  .components-title {
    font-size: 14px;
    color: #222;
    margin: 6px 2px;
    .svg-icon {
      color: #666;
      font-size: 18px;
    }
  }

  .drawing-item {
    .components-body {
      width: 100%;
    }
    .btn-class {
      display: none;
    }
    &:hover {
      .btn-class {
        display: block;
      }
      .components-body {
        width: 90%;
      }
    }
  }

  .components-body {

    padding: 8px 10px;
    background: $selectedColor;
    font-size: 12px;
    cursor: move;
    border: 1px dashed $selectedColor;
    border-radius: 3px;
    .svg-icon {
      color: #777;
      font-size: 15px;
    }
    &:hover {
      border: 1px dashed #787be8;
      color: #787be8;
      .svg-icon {
        color: #787be8;
      }
    }
  }

  .btn-class {
    font-size: xx-small;
  }

  .el-dialog__body {
    display: flex;
    padding: 0 20px;
  }

  .left-board {
    width: 40%;
    height: 66vh;
  }

  .left-scrollbar {
    height: calc(80vh - 42px);
    overflow: hidden;
  }

  .center-scrollbar {
    height: calc(70vh - 42px);
    overflow: hidden;
    border-left: 1px solid #f1e8e8;
    border-right: 1px solid #f1e8e8;
    box-sizing: border-box;
  }

  .center-board {
    height: 70vh;
    width: 60%;
    box-sizing: border-box;
  }

  .empty-info {
    position: absolute;
    top: 46%;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 18px;
    color: #ccb1ea;
    letter-spacing: 4px;
  }

  .center-board-row {
    padding: 12px 12px 15px 12px;
    box-sizing: border-box;
  }

  .drawing-item, .drawing-row-item {
    &:hover {
      & > .el-form-item {
        background: $selectedColor;
        border-radius: 6px;
      }
      & > .drawing-item-copy, & > .drawing-item-delete {
        display: initial;
      }
    }
    & > .drawing-item-copy, & > .drawing-item-delete {
      display: none;
      position: absolute;
      top: -10px;
      width: 22px;
      height: 22px;
      line-height: 22px;
      text-align: center;
      border-radius: 50%;
      font-size: 12px;
      border: 1px solid;
      cursor: pointer;
      z-index: 1;
    }
    & > .drawing-item-copy {
      right: 56px;
      border-color: $lighterBlue;
      color: $lighterBlue;
      background: #fff;
      &:hover {
        background: $lighterBlue;
        color: #fff;
      }
    }
    & > .drawing-item-delete {
      right: 24px;
      border-color: #F56C6C;
      color: #F56C6C;
      background: #fff;
      &:hover {
        background: #F56C6C;
        color: #fff;
      }
    }
  }
</style>
